package com.invoicerecognition.backend.service.impl.teacher;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.invoicerecognition.backend.mapper.TeacherMapper;
import com.invoicerecognition.backend.model.dto.Teacher;
import com.invoicerecognition.backend.model.dto.User;
import com.invoicerecognition.backend.service.impl.utils.UserDetailsImpl;
import com.invoicerecognition.backend.service.teacher.UpdateTeacherInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

@Service
public class UpdateTeacherInfoServiceImpl implements UpdateTeacherInfoService {

    @Autowired
    private TeacherMapper teacherMapper;

    @Override
    public Map<String, String> updateTeacherInfo(Map<String, String> data) {

        String teacherId = data.get("teacherId");
        String name = data.get("name");

        Map<String, String> resp = new HashMap<>();

        if (teacherId.isEmpty()) {
            resp.put("error_message", "工号不能为空");
            return resp;
        }

        if (teacherId.length() > 20) {
            resp.put("error_message", "工号长度超过限制");
            return resp;
        }

        if (name.isEmpty()) {
            resp.put("error_message", "姓名不能为空");
            return resp;
        }

        if (name.length() > 10) {
            resp.put("error_message", "姓名长度超过限制");
            return resp;
        }

        UsernamePasswordAuthenticationToken authentication =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();

        UserDetailsImpl loginUser = (UserDetailsImpl) authentication.getPrincipal();
        User user = loginUser.getUser();

        int userId = user.getId();
        QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        Teacher teacher = teacherMapper.selectOne(queryWrapper);
        if (teacher == null) {
            teacher = new Teacher(null, userId, teacherId, name, new HashSet<>());
            teacherMapper.insert(teacher);
        }
        else {
            teacher.setTeacherId(teacherId);
            teacher.setName(name);
            teacherMapper.updateById(teacher);
        }

        resp.put("error_message", "success");
        resp.put("teacherId", teacherId);
        resp.put("name", name);

        return resp;
    }
}
